package net.sky.oa.dao.talkpark.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sky.oa.dao.SkyBaseDaoImpl;
import net.sky.oa.dao.talkpark.TalBlogDao;
import net.sky.oa.model.TalBlog;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

@SuppressWarnings("unchecked")
@Repository
public class TalBlogDaoImpl extends SkyBaseDaoImpl<TalBlog> implements TalBlogDao{
    
	public TalBlogDaoImpl(){
		super.setPersistType(TalBlog.class);
	}
	
	public List<TalBlog> findAllTalblog() {
		String hql="from TalBlog tbl";
		return findByHql(hql);
	}
	
	public Map findTalBlogByValues(final int type,final String title,final String createtime,final int currentPage,final int lineSize) throws Exception{
		Map map=new HashMap();
	    List list=getHibernateTemplate().executeFind(new HibernateCallback(){
		public Object doInHibernate(Session session) throws HibernateException,
				SQLException {
			StringBuffer buffer=new StringBuffer("from TalBlog tb where 1=1 ");
			StringBuffer cbuffer=new StringBuffer("select count(tb.id) from TalBlog tb where 1=1");
			String hql="";
			if(type!=-1){
				hql=" and tb.type="+type;
				buffer.append(hql);
			    cbuffer.append(hql);
			}
			if(title!=null && !"".equals(title)){
				hql=" and tb.title like '%"+title+"%'";
				buffer.append(hql);
				cbuffer.append(hql);
			}
			if(createtime!=null && !"".equals(createtime)){
				hql=" and to_char(tb.createtime,'yyyy-MM-dd')='"+createtime+"'";
				buffer.append(hql);
				cbuffer.append(hql);
			}
			cbuffer.append("and tb.ispublic=1");
			buffer.append(" and tb.ispublic=1 order by tb.istop asc,tb.createtime desc");
			List resultList = new ArrayList();
			 Long count = (long)0;
			 Query query = session.createQuery(buffer.toString());
			 if(currentPage!=-1&&lineSize!=-1) {
		     count =(Long)session.createQuery(cbuffer.toString()).uniqueResult();
		     resultList = query.setFirstResult((currentPage - 1) * lineSize)
				.setMaxResults(lineSize).list();
			 }else {
					resultList = query.list();
				}
			    List list = new ArrayList();
				list.add(count);
				list.add(resultList);				
			    return list;
		}	
	    });
	    map.put("count",list.get(0) );
        map.put("list", list.get(1) );
                return map;
	}

}
